<template>
  <a-modal title-align="start" title="供应商批量交货" :mask-closable="false" v-model:visible="showvisible" @cancel="showvisible = false" :width="1200">
    <a-table :data="dataList" size="mini" :pagination="false" :scroll="{ x: '100%', y: '400px' }" class="table-two-line mt10">
      <template #columns>
        <a-table-column title="图片" #cell="{ record }" :width="50">
          <a-image @click="showBigImg(record)" :preview="false" :src="$extract(props.getPicList(record)[0], 'url')" width="40" height="40" />
        </a-table-column>
        <a-table-column title="产品SKU" #cell="{ record }" :width="120">
          {{ $extract(record, 'product.productSku') }}
        </a-table-column>
        <a-table-column title="采购公司/采购员" #cell="{ record }" :width="140">
          <div>{{ $extract(record, 'purchaseCompany.companyName ') }}</div>
          <div>{{ $extract(record, 'purchaser.name') }}</div>
        </a-table-column>
        <a-table-column title="定制编号" #cell="{ record }" :width="80">
          {{ record.customCode }}
        </a-table-column>
        <a-table-column title="数量" #cell="{ record }" :width="60">
          {{ record.qtyPurchase }}
        </a-table-column>
        <a-table-column title="定制类型" #cell="{ record }" :width="80">
          {{ $extract(record, 'customInfo.customType') }}
        </a-table-column>
        <a-table-column title="半成品毛坯供应方" #cell="{ record }" :width="120">
          {{ getSupplierName(record) }}
        </a-table-column>
        <a-table-column title="材质" #cell="{ record }" :width="60">
          {{ $extract(record, 'customInfo.material') }}
        </a-table-column>
        <a-table-column :width="120" title="材质单价(元/g)">
          <template #cell="{ record, rowIndex }">{{ $extract(record, 'supplierCloseCost.amtAvgMaterial') }}</template>
        </a-table-column>
        <a-table-column :width="120" title="单件加工费">
          <template #cell="{ record, rowIndex }">{{ $extract(record, 'supplierCloseCost.amtAvgProcess') }}</template>
        </a-table-column>
        <a-table-column :width="160">
          <template #title>
            <a-popover content="材质净重是指产品出库时扣除石头和链条之外的重量。">
              <p>
                <span class="required">材质净重(g)</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">
            <a-space>
              <a-input placeholder="请输入" :disabled="getSupplierName(record) == '需求方'" @change="getAmount(record)" v-model="record.supplierCloseCost.wgtNetMaterial" />
              <a-button size="small" :disabled="record.supplierCloseCost.semiNoPick" class="gray-outline" @click="setGloableDate(rowIndex, record, 'wgtNetMaterial')">
                <template #icon>
                  <icon-double-down />
                </template>
              </a-button>
            </a-space>
          </template>
        </a-table-column>
        <a-table-column :width="160">
          <template #title>
            <a-popover content="生产加工过程中主材质的损耗率">
              <p>
                <span class="required">损耗率(%)</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">
            <a-space>
              <a-input placeholder="请输入" :disabled="getSupplierName(record) == '需求方'" @change="getAmount(record)" v-model="record.supplierCloseCost.attritionRate" />
              <a-button size="small" :disabled="record.supplierCloseCost.semiNoPick" class="gray-outline" @click="setGloableDate(rowIndex, record, 'attritionRate')">
                <template #icon>
                  <icon-double-down />
                </template>
              </a-button>
            </a-space>
          </template>
        </a-table-column>
        <a-table-column :width="120">
          <template #title>
            <a-popover content="连耗重量，是指净重加上损耗的重量。连耗重量=材质净重+（材质净重*损耗率）">
              <p>
                <span class="required">连耗重量(g)</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">{{ $extract(record, 'supplierCloseCost.wgtContinueAttrition') ? $extract(record, 'supplierCloseCost.wgtContinueAttrition') : '--' }}</template>
        </a-table-column>
        <a-table-column :width="100">
          <template #title>
            <a-popover content="材质金额=材质单价*连耗重量">
              <p>
                <span class="required">材质金额</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">{{ $extract(record, 'supplierCloseCost.amtMaterial') ? $extract(record, 'supplierCloseCost.amtMaterial') : '--' }}</template>
        </a-table-column>
        <a-table-column :width="100">
          <template #title>
            <a-popover content="加工费=单件加工费*数量">
              <p>
                <span class="required">加工费</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">{{ record.supplierCloseCost.amtAvgProcess * record.qtyPurchase ? record.supplierCloseCost.amtAvgProcess * record.qtyPurchase : '--' }}</template>
        </a-table-column>

        <a-table-column :width="160">
          <template #title>
            <a-popover content="如果石头是由供应商提供的，则供应商在交货的时可以填上石头费用">
              <p>
                <span class="required">石头费用</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">
            <a-space>
              <a-input placeholder="请输入" @change="getAmount(record)" v-model="record.supplierCloseCost.amtStone" />
              <a-button size="small" class="gray-outline" @click="setGloableDate(rowIndex, record, 'amtStone')">
                <template #icon>
                  <icon-double-down />
                </template>
              </a-button>
            </a-space>
          </template>
        </a-table-column>
        <a-table-column :width="160">
          <template #title>
            <a-popover content="如果链条是由供应商提供的，则供应商在交货的时候可以填上链条费用。">
              <p>
                <span class="required">链条费用</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">
            <a-space>
              <a-input placeholder="请输入" @change="getAmount(record)" v-model="record.supplierCloseCost.amtChain" />
              <a-button size="small" class="gray-outline" @click="setGloableDate(rowIndex, record, 'amtChain')">
                <template #icon>
                  <icon-double-down />
                </template>
              </a-button>
            </a-space>
          </template>
        </a-table-column>
        <a-table-column :width="160">
          <template #title>
            <a-popover content="本次定制单产生的其他费用">
              <p>
                <span class="required">其他费用</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">
            <a-space>
              <a-input placeholder="请输入" @change="getAmount(record)" v-model="record.supplierCloseCost.amtOther" />
              <a-button size="small" class="gray-outline" @click="setGloableDate(rowIndex, record, 'amtOther')">
                <template #icon>
                  <icon-double-down />
                </template>
              </a-button>
            </a-space>
          </template>
        </a-table-column>
        <a-table-column :width="100">
          <template #title>
            <a-popover content="合计金额=材质金额+加工费+石头费用+链条费用+其他费用">
              <p>
                <span class="required">合计金额</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">{{ $extract(record, 'supplierCloseCost.amtTotal') ? $extract(record, 'supplierCloseCost.amtTotal') : '--' }}</template>
        </a-table-column>
        <a-table-column :width="120" title="税率">
          <template #cell="{ record, rowIndex }">
            <div>
              <span> {{ $extract(record, 'supplierCloseCost.taxRate') }}%</span>
              <span class="highlight">{{ record.supplierCloseCost.includeTax ? '（含税）' : '（不含税）' }}</span>
            </div>
          </template>
        </a-table-column>
        <a-table-column :width="120" title="税金">
          <template #cell="{ record, rowIndex }">
            <div>
              <span> {{ $extract(record, 'supplierCloseCost.amtTax') ? $extract(record, 'supplierCloseCost.amtTax') : '--' }}</span>
            </div>
          </template>
        </a-table-column>
        <a-table-column :width="60" title="操作" #cell="{ record, rowIndex }" fixed="right">
          <a-button type="text" style="color: red" @click="dataList.splice(rowIndex, 1)">移除 </a-button>
        </a-table-column>
      </template>
    </a-table>
    <template #footer class="modal-footer">
      <a-button @click="showvisible = false">取消</a-button>
      <a-button type="primary" :loading="submitLoading" @click="submit">确定</a-button>
    </template>
  </a-modal>
  <a-image-preview-group v-model:visible="visible" infinite :srcList="srcList" />
</template>

<script lang="ts" setup>
  import { onMounted, ref, computed } from 'vue'
  import { batchSupplierSubmitVerify } from '@/api/purchase'
  import { Message } from '@arco-design/web-vue'
  import _ from 'lodash-es'
  let props = defineProps(['modelValue', 'type', 'ids', 'list', 'getfittingName', 'getPicList'])
  let emits = defineEmits(['save', 'update:modelValue'])
  let showvisible = computed({
    get() {
      return props.modelValue
    },
    set(val) {
      emits('update:modelValue', val)
    },
  })
  let dataList = ref<Array<any>>([])
  let srcList = ref([])
  let visible = ref(false)
  let submitLoading = ref(false)
  const init = () => {
    props.ids.forEach((e: any) => {
      let item = _.cloneDeep(props.list.find((item: any) => item.id == e))
      if (item) {
        let obj = {
          ...item,
        }
        console.log(obj)
        obj.supplierCloseCost.amtProcess = obj?.supplierCloseCost?.amtAvgProcess || 0 * obj.qtyPurchase
        dataList.value.push(obj)
      }
    })

    console.log(dataList.value)
  }

  const showBigImg = (item: any) => {
    let arr = props.getPicList(item)
    srcList.value = arr.map((e: any) => e.url)
    visible.value = true
  }

  function formatFloatToFourDecimalPlaces(num: any) {
    // 将数字转换为字符串
    let numStr = num.toString()

    // 检查是否包含小数点
    if (numStr.includes('.')) {
      // 如果包含小数点，则使用 toFixed 保留四位小数
      return parseFloat(num.toFixed(4)).toString()
    } else {
      // 如果不包含小数点（即整数），则直接返回原字符串
      return numStr
    }
  }

  const getAmount = (data: any) => {
    let w = 0
    let obj = data?.supplierCloseCost || {}

    w = Number(obj.wgtNetMaterial) + Number(obj.wgtNetMaterial * (obj.attritionRate / 100))
    obj.wgtContinueAttrition = formatFloatToFourDecimalPlaces(w)

    obj.amtMaterial = formatFloatToFourDecimalPlaces(obj.wgtContinueAttrition * data.supplierCloseCost.amtAvgMaterial)

    let num1 = obj.amtMaterial ? parseFloat(obj.amtMaterial) : 0
    let num2 = formatFloatToFourDecimalPlaces(data.supplierCloseCost.amtAvgProcess * data.qtyPurchase) ? parseFloat(formatFloatToFourDecimalPlaces(data.supplierCloseCost.amtAvgProcess * data.qtyPurchase)) : 0
    let num3 = obj.amtStone ? parseFloat(obj.amtStone) : 0
    let num4 = obj.amtChain ? parseFloat(obj.amtChain) : 0
    let num5 = obj.amtOther ? parseFloat(obj.amtOther) : 0

    obj.amtTotal = formatFloatToFourDecimalPlaces(num1 + num2 + num3 + num4 + num5)

    obj.amtTax = formatFloatToFourDecimalPlaces((obj.amtTotal * data.supplierCloseCost.taxRate) / 100)
  }

  const setGloableDate = (index: number, data: any, type: string) => {
    dataList.value.forEach((e: any, i: number) => {
      if (i > index) {
        e.supplierCloseCost[type] = data.supplierCloseCost[type]
        getAmount(e)
      }
    })
  }

  const submit = async () => {
    let params = {
      list: dataList.value,
    }

    try {
      submitLoading.value = true
      const res: any = await batchSupplierSubmitVerify(params)
      if (res) {
        Message.success('交货成功')
        showvisible.value = false
        emits('save')
      }
    } catch (error) {}
    submitLoading.value = false
  }

  const getSupplierName = (data: any) => {
    if (data.supplierCloseCost.semiNoPick) {
      return '供应商'
    } else {
      return data.supplierCloseCost.semiWarehouseCode == 'CK86' ? '需求方' : '采购方'
    }
  }

  onMounted(() => {
    init()
  })
</script>

<style lang="less" scoped></style>
